let ws = require("nodejs-websocket");
process.stdin.setEncoding("utf8");
console.log("开始建立连接...");
let userObj = {};
let server = ws.createServer(function (conn) {
    conn.on("text", function (str) {
        console.log(str);
        let newStr = eval("(" + str + ")");
        const { memberId, targetId, content } = newStr;
        console.log("收到的信息为:" + content);
        console.log("用户id:" + memberId);
        userObj[memberId] = {
            coon: conn,
            isOnline: true,
        };
        // console.log(userObj);
        if (content !== "已经建立连接") {
            //如果接收方在线
            if (userObj[targetId]) {
                userObj[targetId].coon.sendText(memberId + ":" + content);
            } else {
                conn.sendText("对方不在线")
            }
            conn.sendText(memberId + ":" + content);
        }

        //像前端页面发送推送
        process.stdout.write("请输入发送的值：");
        process.stdin.on("data", function (chunk) {
            conn.sendText(chunk);
        });
    });

    conn.on("close", function (code, reason) {
        console.log("关闭连接");
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭");
    });
}).listen(8801);
console.log("WebSocket建立完毕");

module.exports = server